/*
 * ListenerPort.cpp
 *
 *  Created on: Mar 16, 2009
 *      Author: Andrzej Olchawa
 *      mailto: andrzejolchawa@gmail.com
 *      http://www.hardtechnology.org
 *      This is a part of the Armazd project, which is covered by
 *      GNU GPL v2 license.
 */

#include "ListenerPort.h"
#include "HTFramework/HTThread.cpp"

ListenerPort::ListenerPort() {}

ListenerPort::ListenerPort(string name, int port)
{
	listenerName = name;
	this->port = port;
	initListener();
	start();
}

ListenerPort::~ListenerPort()
{
	close(hSocket);
}

void ListenerPort::run()
{
	char buf[SIZE_OF_LISTENER_BUFFER];

	while (true)
	{
		buf[0] = '\0';
		struct sockaddr_in from;
		socklen_t fromlen;

		bzero(buf,sizeof(buf));
		recvfrom(hSocket, buf, SIZE_OF_LISTENER_BUFFER, 0, (struct sockaddr *) &from, &fromlen);

		cout << buf << endl;

//		try
//		{
//			sender->sendData(string(buf));
//		}
//		catch (AgentException &e)
//		{
//			e.printException();
//		}
	}

}

void ListenerPort::initListener()
{
	hSocket = socket(PF_INET, SOCK_DGRAM, 0);
	if (hSocket < 0)
	{
		throw AgentException("ListenerPort.initListener(): can't create socket: " + string(strerror(errno)));
	}

	addr.sin_family=PF_INET;
	addr.sin_port=htons(port);

	addr.sin_addr.s_addr=INADDR_ANY;

	int res = bind(hSocket, (struct sockaddr *) &addr, sizeof(struct sockaddr_in));
	if (res < 0)
	{
		throw AgentException("ListenerPort.initListener(): can't open port: " + string(strerror(errno)));
	}
}
